<template>
	<view class="add-pet-container">
		<view class="header">
			<image class="paw-print header-paw" src="/static/img/paw-print.svg" mode="aspectFit"></image>
			<text class="title">添加萌宠</text>
		</view>
		
		<view class="form-container">
			<view class="form-item">
				<text class="label">宠物形象</text>
				<view class="style-selector">
					<view v-if="isLoadingTemplates" class="loading-tips">
						<text>加载模板中...</text>
					</view>
					<view v-else-if="filteredTemplates.length === 0" class="empty-tips">
						<text>暂无{{formData.type === 'cat' ? '猫咪' : '狗狗'}}模板</text>
					</view>
					<scroll-view class="template-scroll" scroll-x v-else>
						<view class="template-list">
							<view class="template-item" 
								v-for="template in filteredTemplates" 
								:key="template.objectId"
								:class="{'selected': selectedTemplateId === template.objectId}"
								@tap="selectTemplate(template)">
								<image class="template-image" :src="template.imageUrl" mode="aspectFit"></image>
								<text class="template-name">{{template.species}}</text>
							</view>
						</view>
					</scroll-view>
					<button class="use-template-btn" 
						@tap="useTemplate"
						:disabled="!selectedTemplateId">
						使用此形象
					</button>
				</view>
			</view>
			
			<view class="form-group">
				<view class="form-item">
					<text class="label">萌宠名称</text>
					<input class="input" v-model="formData.name" placeholder="给萌宠起个名字吧" />
				</view>
				
				<view class="form-item">
					<text class="label">萌宠类型</text>
					<view class="type-selector">
						<view class="type-option" 
							:class="{'selected': formData.type === 'cat'}"
							@tap="formData.type = 'cat'">
							<image class="type-icon" src="../../static/img/cat-icon.png" mode="aspectFit"></image>
							<text class="type-text">猫咪</text>
						</view>
						<view class="type-option"
							:class="{'selected': formData.type === 'dog'}"
							@tap="formData.type = 'dog'">
							<image class="type-icon" src="../../static/img/dog-icon.png" mode="aspectFit"></image>
							<text class="type-text">狗狗</text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="submit-section">
				<button class="submit-btn" @tap="submitForm">确认添加</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					avatar: '',
					name: '',
					type: 'cat',
					mood: 100,
					hunger: 100,
					energy: 100,
					exp: 0,
					level: 1,
					lastFeed: '',
					lastPlay: '',
					statistics: {
						totalFeeds: 0,
						totalPlays: 0,
						favoriteFood: '',
						moodHistory: []
					}
				},
				petTypes: ['猫咪', '狗狗'],
				typeIndex: 0,
				genderTypes: ['公', '母'],
				genderIndex: 0,
				showAdvancedSettings: false,
				templates: [],
				selectedTemplateId: '',
				filteredTemplates: [],
				isLoadingTemplates: true
			}
		},
		watch: {
			'formData.type'(newType) {
				this.filterTemplates(newType)
			}
		},
		methods: {
			onTypeChange(e) {
				this.typeIndex = e.detail.value;
				this.formData.type = this.typeIndex === 0 ? 'cat' : 'dog';
			},
			
			onGenderChange(e) {
				this.genderIndex = e.detail.value;
				this.formData.gender = this.genderIndex === 0 ? 'male' : 'female';
			},
			
			onBirthdayChange(e) {
				this.formData.birthday = e.detail.value;
			},
			
			async submitForm() {
				try {
					if (!this.validateForm()) return;
					
					uni.showLoading({ title: '保存中...' });
					
					const user = await this.$leanCloud.user.getCurrent();
					if (!user) throw new Error('用户未登录');
					
					const pets = await this.$leanCloud.query('Pet', {
						user: {
							__type: 'Pointer',
							className: '_User',
							objectId: user.objectId
						}
					});
					
					if (pets && pets.results && pets.results.length > 0) {
						throw new Error('您已经有一个宠物了');
					}
					
					const petData = {
						user: {
							__type: 'Pointer',
							className: '_User',
							objectId: user.objectId
						},
						avatar: this.formData.avatar,
						name: this.formData.name.trim(),
						type: this.formData.type,
						mood: 100,
						hunger: 100,
						energy: 100,
						exp: 0,
						level: 1,
						lastFeed: new Date(),
						lastPlay: new Date(),
						statistics: {
							totalFeeds: 0,
							totalPlays: 0,
							favoriteFood: '',
							moodHistory: []
						}
					};
					
					await this.$leanCloud.create('Pet', petData);
					
					uni.hideLoading();
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
					
					setTimeout(() => {
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						if (prevPage && prevPage.$vm.loadPetInfo) {
							prevPage.$vm.loadPetInfo();
						}
						uni.navigateBack();
					}, 1500);
					
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '保存失败',
						icon: 'none'
					});
					console.error('保存宠物信息失败:', error);
				}
			},
			
			validateForm() {
				const { name, type, avatar } = this.formData;
				
				if (!avatar) {
					uni.showToast({
						title: '请选择宠物形象',
						icon: 'none'
					});
					return false;
				}
				
				if (!name.trim()) {
					uni.showToast({
						title: '请输入萌宠名字',
						icon: 'none'
					});
					return false;
				}
				
				if (name.length > 10) {
					uni.showToast({
						title: '萌宠名字不能超过10个字',
						icon: 'none'
					});
					return false;
				}
				
				if (!['cat', 'dog'].includes(type)) {
					uni.showToast({
						title: '请选择正确的宠物类型',
						icon: 'none'
					});
					return false;
				}
				
				return true;
			},
			
			selectStyle(style) {
				this.formData.style = style;
			},
			
			async checkLoginStatus() {
				try {
					const user = await this.$leanCloud.user.getCurrent();
					if (!user) {
						uni.redirectTo({
							url: '/pages/login/wechatEntry'
						});
						return;
					}
					
					const pets = await this.$leanCloud.query('Pet', {
						user: {
							__type: 'Pointer',
							className: '_User',
							objectId: user.objectId
						}
					});
					
					if (pets && pets.results && pets.results.length > 0) {
						uni.showModal({
							title: '提示',
							content: '您已经有一个宠物了',
							showCancel: false,
							success: () => {
								uni.navigateBack();
							}
						});
					}
				} catch (error) {
					console.error('检查登录状态失败:', error);
					uni.showToast({
						title: '系统错误',
						icon: 'none'
					});
				}
			},
			
			async loadTemplates() {
				try {
					this.isLoadingTemplates = true
					console.log('开始加载宠物模板...')
					uni.showLoading({
						title: '加载模板中...'
					})
					
					const result = await this.$leanCloud.query('PetTemplate')
					console.log('模板查询结果:', result)
					
					if (result && result.results) {
						this.templates = result.results
						console.log('获取到的模板:', this.templates)
						this.filterTemplates(this.formData.type)
					} else {
						console.error('模板数据格式异常:', result)
						this.templates = []
					}
					
					uni.hideLoading()
					this.isLoadingTemplates = false
				} catch (error) {
					console.error('加载模板失败：', error)
					uni.showToast({
						title: '加载模板失败',
						icon: 'none'
					})
					this.isLoadingTemplates = false
					uni.hideLoading()
				}
			},
			
			filterTemplates(type) {
				// 将宠物类型英文映射到中文类别
				const categoryMap = {
					'cat': '猫',
					'dog': '狗'
				}
				const category = categoryMap[type]
				
				console.log('过滤模板:', {type, category, templates: this.templates})
				
				if (!this.templates || this.templates.length === 0) {
					console.log('没有可用模板')
					this.filteredTemplates = []
					
					// 如果没有模板，给用户提示
					uni.showToast({
						title: '暂无可用模板，请联系管理员添加',
						icon: 'none',
						duration: 2000
					})
					return
				}
				
				// 过滤出当前所选类型的模板
				this.filteredTemplates = this.templates.filter(t => t.category === category)
				console.log('过滤后的模板:', this.filteredTemplates)
				
				// 如果过滤后没有模板，给用户提示
				if (this.filteredTemplates.length === 0) {
					uni.showToast({
						title: `暂无${type === 'cat' ? '猫咪' : '狗狗'}模板，请联系管理员添加`,
						icon: 'none',
						duration: 2000
					})
				}
				
				// 重置选中状态
				this.selectedTemplateId = ''
			},
			
			selectTemplate(template) {
				this.selectedTemplateId = template.objectId
			},
			
			useTemplate() {
				if (!this.selectedTemplateId) return
				
				const template = this.templates.find(t => t.objectId === this.selectedTemplateId)
				if (!template) return
				
				this.formData.avatar = template.imageUrl
				this.formData.style = template.species
				
				uni.showToast({
					title: '已应用模板',
					icon: 'success'
				})
			}
		},
		onLoad() {
			this.checkLoginStatus();
			this.loadTemplates();
		}
	}
</script>

<style lang="scss">
	.add-pet-container {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding: 30rpx;
		
		.header {
			display: flex;
			align-items: center;
			margin-bottom: 40rpx;
			
			.header-paw {
				width: 48rpx;
				height: 48rpx;
				margin-right: 16rpx;
			}
			
			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #6C3FFF;
			}
		}
		
		.form-container {
			background-color: #fff;
			border-radius: 24rpx;
			padding: 30rpx;
			
			.form-item {
				margin-bottom: 30rpx;
				
				.label {
					display: block;
					font-size: 28rpx;
					color: #333;
					margin-bottom: 16rpx;
				}
				
				.input {
					width: 100%;
					height: 80rpx;
					background-color: #f8f8f8;
					border-radius: 12rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #333;
				}
				
				.type-selector {
					display: flex;
					justify-content: space-between;
					
					.type-option {
						flex: 1;
						height: 120rpx;
						background-color: #f8f8f8;
						border-radius: 12rpx;
						margin: 0 10rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						transition: all 0.3s ease;
						
						&.selected {
							background-color: rgba(139, 92, 255, 0.1);
							border: 2rpx solid #8B5CFF;
							
							.type-text {
								color: #8B5CFF;
							}
						}
						
						.type-icon {
							width: 48rpx;
							height: 48rpx;
							margin-bottom: 8rpx;
						}
						
						.type-text {
							font-size: 26rpx;
							color: #666;
						}
					}
				}
			}
			
			.style-selector {
				margin-top: 20rpx;
				
				.loading-tips, .empty-tips {
					height: 150rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #f8f8f8;
					border-radius: 12rpx;
					margin-bottom: 20rpx;
					
					text {
						font-size: 28rpx;
						color: #999;
					}
				}
				
				.template-scroll {
					width: 100%;
					white-space: nowrap;
					margin-bottom: 20rpx;
					
					.template-list {
						display: inline-flex;
						padding: 10rpx;
						
						.template-item {
							display: inline-flex;
							flex-direction: column;
							align-items: center;
							margin-right: 20rpx;
							padding: 10rpx;
							border: 2rpx solid #f0f0f0;
							border-radius: 12rpx;
							width: 160rpx;
							
							&.selected {
								border-color: #8B5CFF;
								background-color: rgba(139, 92, 255, 0.1);
							}
							
							.template-image {
								width: 120rpx;
								height: 120rpx;
								border-radius: 8rpx;
								margin-bottom: 10rpx;
							}
							
							.template-name {
								font-size: 24rpx;
								color: #666;
								width: 100%;
								text-align: center;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
							}
						}
					}
				}
				
				.use-template-btn {
					background-color: #8B5CFF;
					color: #fff;
					font-size: 28rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 30rpx;
					margin-top: 20rpx;
					
					&[disabled] {
						background-color: #ccc;
						color: #fff;
					}
				}
			}
			
			.submit-section {
				.submit-btn {
					width: 100%;
					height: 88rpx;
					background: linear-gradient(135deg, #8B5CFF 0%, #6C3FFF 100%);
					border-radius: 44rpx;
					color: #fff;
					font-size: 32rpx;
					font-weight: bold;
					display: flex;
					align-items: center;
					justify-content: center;
					
					&:active {
						opacity: 0.8;
					}
				}
			}
		}
	}
</style> 